<template>
  <div class="dashboard">
    <TopNavbar />
    <Sidebar />
    <div class="user-management-content">
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span>用户管理</span>
          </div>
        </template>
        <div class="search-header">
          <el-form :inline="true" class="demo-form-inline" @submit.prevent>
            <el-form-item>
              <el-input
                v-model="searchQuery"
                placeholder="搜索账号"
                prefix-icon="el-icon-search"
                @change="handleSearch"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="resetSearch">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <el-table :data="users" style="width: 100%" @row-click="handleRowClick">
          <el-table-column fixed="left" width="100" header-align="center" align="center" label="头像">
            <template #default="{ row }">
              <img :src="row.avatarUrl ? row.avatarUrl : 'https://crazyhat.oss-cn-beijing.aliyuncs.com/img/3c3c9bd7-ab8b-41e6-9954-051abf8d3098.png'" alt="Avatar" style="width: 50px; height: 50px; border-radius: 50%;">
            </template>
          </el-table-column>

          <el-table-column prop="name" label="姓名" width="180" header-align="center" align="center"></el-table-column>
          <el-table-column prop="studentId" label="学号" width="180" header-align="center" align="center"></el-table-column>
          <el-table-column prop="gender" label="性别" header-align="center" align="center"></el-table-column>
          <el-table-column prop="age" label="年龄" header-align="center" align="center"></el-table-column>
          <el-table-column prop="email" label="邮箱" header-align="center" align="center"></el-table-column>
          <el-table-column
            prop="createTime"
            label="账号创建时间"
            header-align="center"
            align="center"
          ></el-table-column>
          <el-table-column label="操作" header-align="center" align="center">
            <template #default="{ row }">
              <el-dropdown>
                <el-button type="text">
                  操作
                  <i class="el-icon-arrow-down el-icon--right"></i>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="editUser(row)">修改</el-dropdown-item>
                    <el-dropdown-item @click="deleteUser(row)">删除</el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>

        <el-dialog
            v-model="dialogVisible"
            title="修改用户信息"
            width="400px"
            :close-on-click-modal="false"
            :show-close="false"
        >
          <el-form :model="editForm" label-width="80px" @submit.prevent="submitEdit">
            <el-form-item label="头像">
              <div class="avatar-uploader">
                <img v-if="previewUrl" :src="previewUrl" class="avatar-preview" alt="Avatar Preview">
                <div v-else class="avatar-placeholder">
                  <el-icon><Plus /></el-icon>
                </div>
                <input
                    type="file"
                    @change="handleFileChange"
                    accept="image/*"
                    class="file-input"
                    ref="fileInput"
                >
              </div>
              <el-button size="small" type="primary" @click="triggerFileInput">选择图片</el-button>
            </el-form-item>
            <el-form-item label="姓名">
              <el-input v-model="editForm.name" placeholder="请输入姓名"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEdit">确认</el-button>
      </span>
          </template>
        </el-dialog>
      </el-card>

    </div>
  </div>
</template>

<script>
import Sidebar from '@/components/Sidebar.vue';
import TopNavbar from '@/components/TopNavbar.vue';
import axios from "axios";
import {ElMessageBox} from "element-plus";
import { Plus } from '@element-plus/icons-vue'
// import { format } from 'date-fns';

export default {
  name: 'UserManagement',
  components: {
    Sidebar,
    TopNavbar
  },
  data() {
    return {
      searchQuery: '',
      users:[],
      dialogVisible: false,
      editForm: {
        avatar: null,
        name: '',
        studentId: '',
      },
      previewUrl: null
    };
  },
  created() {
    this.searchAll();
  },
  methods: {

    handleSearch() {
      if(this.searchQuery===""){
        this.searchAll();
      }else{
        this.searchUser(this.searchQuery)
      }
    },
    resetSearch() {
      this.searchQuery = '';
    },
    handleRowClick(row, column, event) {
      // 行点击逻辑
    },
    editUser(user) {
      this.editForm = {
        avatarUrl: user.avatarUrl,
        name: user.name,
        studentId: user.studentId,
      };
      this.dialogVisible = true;
      this.previewUrl=user.avatarUrl;
    },
    handleFileChange(event) {
      const file = event.target.files[0];
      if (file) {
        this.editForm.avatar = file;
        this.previewUrl = URL.createObjectURL(file);
      }
    },

    triggerFileInput() {
      this.$refs.fileInput.click()
    },

    async submitEdit() {
      const formData = new FormData();
      formData.append('avatar', this.editForm.avatar);
      formData.append('name', this.editForm.name);
      formData.append('studentId', this.editForm.studentId);

      try {
        const response = await axios.post('/user/adminModifyUserInfo', formData, {
          headers: {
            'Content-Type': 'multipart/form-data',
            'Authorization': sessionStorage.getItem('token')
          }
        });

        if (response.data.code === 0) {
          this.$message.success('修改成功');
          this.dialogVisible = false;
          // 更新本地数据
          const index = this.users.findIndex(u => u.studentId === this.editForm.studentId);
          if (index !== -1) {
            this.users[index].avatarUrl = response.data.data.avatarUrl; // 假设后端返回了新的头像URL
            this.users[index].name = this.editForm.name;
          }
        } else {
          this.$message.error('修改失败: ' + response.data.message);
        }
      } catch (error) {
        console.error('Error updating user:', error);
        this.$message.error('修改失败，请稍后重试');
      }
    },
    async deleteUser(row){
      ElMessageBox.confirm('您确定要删除这个用户吗?', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDeleteUser(row); // 直接传递 clubId 的数组
      }).catch(() => {
        this.$message.success('操作已取消');
      });
    },

    async handleDeleteUser(row) {
      try {
        const params=[row.studentId];
        const response = await axios.delete('/user/delete',{data:params});
        if (response.data.code === 0) {
          this.users = this.users.filter(user => user.studentId !== row.studentId);
          this.$message.success("删除成功！");
        } else {
          console.error('未能成功删除:', response.data.message);
        }
      } catch (error) {
        console.error('删除时出现错误:', error);
      }
    },
    async searchAll(){
      try {
        const response = await axios.get('/user/all');
        console.log(response)
        if (response.data.code === 0) {
          this.users = response.data.data;
        } else {
          console.error('Failed to fetch search user:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching search user:', error);
      }
    },


    async searchUser(userId) {
      try {
        const response = await axios.get('/user/userinfo', { params:{studentId:userId} });
        if (response.data.code === 0&&response.data.data!==null) {
          this.users = [response.data.data];
        } else {
          console.error('Failed to fetch search user:', response.data.message);
        }
      } catch (error) {
        console.error('Error fetching search user:', error);
      }
    }
  }
};
</script>

<style scoped>
.dashboard {
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  position: relative;
  background: #ffffff;
}

.top-nav {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 10;
}

.sidebar {
  width: 250px;
  position: fixed;
  left: 0;
  top: 60px;
  bottom: 0;
  overflow-y: auto;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
  background: #fff;
}

.user-management-content {
  flex-grow: 1;
  margin-left: 250px;
  padding: 20px;
  padding-top: 80px; /* Adjusted to match the TopNavbar height */
  overflow-y: auto;
  overflow-x: hidden;
}

.box-card {
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.el-form-item {
  margin-bottom: 0;
}

.el-button {
  margin-left: 10px;
}

.el-table {
  margin-top: 10px;
}

.el-pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.dialog-footer .el-button {
  margin-left: 10px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader {
  width: 178px;
  height: 178px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;
}
.avatar-uploader:hover {
  border-color: #409EFF;
}
.avatar-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}
.avatar-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 28px;
  color: #8c939d;
}
.file-input {
  display: none;
}
.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
@media (max-width: 768px) {
  .top-nav {
    left: 0;
  }

  .sidebar {
    width: 100%;
    position: relative;
  }

  .user-management-content {
    margin-left: 0;
    padding: 10px;
  }

  .search-header {
    flex-direction: column;
    align-items: stretch;
  }

  .el-form-item {
    margin-bottom: 10px;
  }

  .el-button {
    width: 100%;
    margin-left: 0;
    margin-top: 10px;
  }
}
</style>
